package com.thx.common.orm;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.CacheMode;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.thx.common.orm.model.Property;

/**
 * 带扩展的翻页查询.
 */
@Repository
public class PropertyDao extends PaginationDao<Property> {

  /**
   * 根据模板id查询启用的属性.
   */
  public List<Property> findByTemplateId(String templateId) {
    String hql = "from Property where templateId = ? and state = '启用' order by seqNum asc";
    Query query = createQuery(hql, templateId);
    List<Property> list = query.list();

    // 下面循环用来处理因hibernate缓存导致上次查询后，经过业务处理后给Property对象附加了额外的属性信息，从而导致再次查询得到的Property对象携带了上次业务信息
    for (Property p : list) {
      p.setPropertyVal(null);
    }

    return list;
  }

  /**
   * 根据模版id和模版别名查询属性.
   */
  public List<Property> findPropsByTplIdAndName(String tlpId, String aliasName) {
    String hql = "from Property where 1=1  ";
    List<String> params = new ArrayList<String>();
    if (StringUtils.isNotBlank(tlpId)) {
      hql += " and templateId=? ";
      params.add(tlpId);
    }
    if (StringUtils.isNotBlank(aliasName)) {
      hql += " and aliasName like ? ";
      params.add("%" + aliasName + "%");
    }
    hql += " order by seqNum asc";
    List<Property> list = findPageList(hql, params.toArray());
    return list;
  }
}
